package net.toby200.canalbuddy.notices.gcm;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.Gson;

import net.toby200.canalbuddy.notices.model.Notice;
import net.toby200.canalbuddy.notices.notification.NoticeNotificationManager;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by toby on 31/07/2014.
 */
public class GcmIntentService extends IntentService {
    private static final Logger LOG = Logger.getLogger(GcmReceiver.class.getName());


    NoticeNotificationManager noticeManager;

    public GcmIntentService() {
        super("GcmIntentService");
        LOG.info("Creating GCMIntentService");
        noticeManager = new NoticeNotificationManager();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        LOG.info("onHandleIntent");
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (extras != null && !extras.isEmpty()) {
            // Since we're not using two way messaging, this is all we really to check for
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                LOG.log(Level.INFO, extras.toString());
                try {
                    Context context = getApplicationContext();
                    String gson = extras.getString("notice");
                    Notice notice = new Gson().fromJson(gson, Notice.class);
                    LOG.info("Notice updated: " + notice);
                    Intent notificationIntent = new Intent(context, NoticeNotificationManager.class);
                    notificationIntent.putExtra("net.toby200.canalbuddy.NOTICE", notice);
                    context.startService(notificationIntent);

                } catch (Exception e) {
                    LOG.log(Level.SEVERE, "Error processing notification", e);
                }
            }
        }
        GcmReceiver.completeWakefulIntent(intent);
    }

}
